<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>纸片化学·实验者</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.1/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        :root {
            --primary: #3498db;
            --secondary: #2ecc71;
            --danger: #e74c3c;
            --warning: #f39c12;
            --dark: #2c3e50;
            --light: #ecf0f1;
            --success: #27ae60;
            --gray: #95a5a6;
            --card-width: 80px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #1a2a6c, #2c3e50);
            color: var(--light);
            min-height: 100vh;
            padding: 20px;
            overflow-x: hidden;
        }

        .game-container {
            display: grid;
            grid-template-columns: 250px 1fr 300px;
            grid-template-rows: auto 1fr auto;
            gap: 15px;
            height: calc(100vh - 40px);
            max-width: 1800px;
            margin: 0 auto;
        }

        /* 头部区域 */
        .header {
            grid-column: 1 / -1;
            background: rgba(44, 62, 80, 0.7);
            border-radius: 10px;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .room-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .phase-indicator {
            padding: 8px 15px;
            border-radius: 20px;
            font-weight: bold;
            text-transform: uppercase;
            font-size: 14px;
        }

        .phase-preparation { background: var(--warning); color: #000; }
        .phase-action { background: var(--danger); }
        .phase-defense { background: var(--secondary); }
        .phase-settlement { background: var(--gray); }
        .phase-distributing { background: var(--primary); }

        .player-health {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 20px;
            font-weight: bold;
        }

        .health-bar {
            width: 200px;
            height: 20px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            overflow: hidden;
        }

        .health-fill {
            height: 100%;
            background: linear-gradient(to right, var(--danger), var(--warning), var(--success));
            transition: width 0.5s ease;
        }

        /* 玩家列表 */
        .player-list {
            grid-column: 1;
            grid-row: 2;
            background: rgba(44, 62, 80, 0.7);
            border-radius: 10px;
            padding: 15px;
            overflow-y: auto;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .player-card {
            background: rgba(52, 152, 219, 0.3);
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 12px;
            transition: all 0.3s ease;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .player-card.current-turn {
            background: rgba(243, 156, 18, 0.4);
            box-shadow: 0 0 10px rgba(243, 156, 18, 0.5);
        }

        .player-card.eliminated {
            background: rgba(231, 76, 60, 0.3);
            opacity: 0.7;
        }

        .player-card.under-attack {
            animation: pulse 1.5s infinite;
            border: 2px solid var(--danger);
        }

        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(231, 76, 60, 0); }
            100% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0); }
        }

        .player-name {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-weight: bold;
            font-size: 16px;
        }

        .player-role {
            font-size: 12px;
            opacity: 0.8;
        }

        .player-status {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
        }

        /* 游戏区域 */
        .game-area {
            grid-column: 2;
            grid-row: 2;
            display: grid;
            grid-template-rows: auto 1fr auto;
            gap: 15px;
        }

        .card-section {
            background: rgba(44, 62, 80, 0.7);
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .section-title {
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 18px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            padding-bottom: 10px;
        }

        .cards-container {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            min-height: 120px;
        }

        .card {
            width: var(--card-width);
            height: calc(var(--card-width) * 1.4);
            background: linear-gradient(135deg, #3498db, #2980b9);
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            font-weight: bold;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            cursor: pointer;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }

        .card.atom { background: linear-gradient(135deg, #3498db, #2980b9); }
        .card.acid { background: linear-gradient(135deg, #2ecc71, #27ae60); }
        .card.action { background: linear-gradient(135deg, #e74c3c, #c0392b); }
        .card.compound { background: linear-gradient(135deg, #9b59b6, #8e44ad); }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.4);
        }

        .card.selected {
            box-shadow: 0 0 0 3px var(--warning);
            transform: translateY(-5px);
        }

        .card .card-label {
            font-size: 12px;
            margin-top: 5px;
            text-align: center;
        }

        .compound-properties {
            position: absolute;
            bottom: 5px;
            font-size: 10px;
            display: flex;
            gap: 3px;
        }

        .property-tag {
            background: rgba(0, 0, 0, 0.4);
            padding: 2px 5px;
            border-radius: 10px;
            font-size: 10px;
        }

        .property-corrosive { color: #f39c12; }
        .property-poison { color: #27ae60; }
        .property-gas { color: #3498db; }

        /* 操作面板 */
        .action-panel {
            grid-column: 3;
            grid-row: 2;
            background: rgba(44, 62, 80, 0.7);
            border-radius: 10px;
            padding: 15px;
            overflow-y: auto;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .action-title {
            font-size: 18px;
            margin-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            padding-bottom: 10px;
        }

        .action-buttons {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .btn {
            padding: 12px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            color: white;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .btn-primary {
            background: linear-gradient(to right, var(--primary), #2980b9);
        }

        .btn-secondary {
            background: linear-gradient(to right, var(--secondary), #27ae60);
        }

        .btn-warning {
            background: linear-gradient(to right, var(--warning), #d35400);
        }

        .btn-danger {
            background: linear-gradient(to right, var(--danger), #c0392b);
        }

        .btn:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }

        .action-section {
            margin-top: 25px;
        }

        .action-section-title {
            font-size: 16px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border-radius: 6px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.2);
            color: white;
            font-size: 16px;
        }

        .target-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .target-item {
            padding: 10px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .target-item:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* 日志区域 */
        .log-area {
            grid-column: 1 / -1;
            grid-row: 3;
            background: rgba(44, 62, 80, 0.7);
            border-radius: 10px;
            padding: 15px;
            max-height: 200px;
            overflow-y: auto;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .log-title {
            font-size: 18px;
            margin-bottom: 10px;
        }

        .log-messages {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .log-message {
            padding: 8px 10px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 5px;
            font-size: 14px;
        }

        .log-message.attack { border-left: 4px solid var(--danger); }
        .log-message.defense { border-left: 4px solid var(--secondary); }
        .log-message.system { border-left: 4px solid var(--primary); }
        .log-message.chemistry { border-left: 4px solid var(--warning); }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: linear-gradient(to bottom, #2c3e50, #1a2a6c);
            width: 90%;
            max-width: 500px;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .modal-title {
            font-size: 24px;
            margin-bottom: 20px;
            text-align: center;
            color: white;
        }

        .modal-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .compound-inputs {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }

        .formula-preview {
            text-align: center;
            font-size: 32px;
            font-weight: bold;
            margin: 15px 0;
            min-height: 45px;
        }

        .modal-buttons {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }

        .modal-buttons .btn {
            flex: 1;
        }

        /* 响应式设计 */
        @media (max-width: 1200px) {
            .game-container {
                grid-template-columns: 200px 1fr;
            }

            .action-panel {
                grid-column: 1 / -1;
                grid-row: 3;
            }

            .log-area {
                grid-row: 4;
            }
        }

        @media (max-width: 768px) {
            .game-container {
                grid-template-columns: 1fr;
                grid-template-rows: auto auto auto auto auto;
            }

            .player-list {
                grid-column: 1;
                grid-row: 2;
            }

            .game-area {
                grid-column: 1;
                grid-row: 3;
            }

            .action-panel {
                grid-column: 1;
                grid-row: 4;
            }

            .log-area {
                grid-row: 5;
            }

            .card {
                width: 70px;
                height: calc(70px * 1.4);
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <!-- 头部区域 -->
        <div class="header">
            <div class="room-info">
                <div class="room-id">
                    <i class="fas fa-door-open"></i> 房间: <span id="room-id">加载中...</span>
                </div>
                <div class="phase-indicator phase-preparation" id="phase-indicator">准备阶段</div>
                <div class="turn-indicator">
                    <i class="fas fa-user-clock"></i> 当前回合: <span id="current-player">加载中...</span>
                </div>
            </div>
            <div class="player-health">
                <i class="fas fa-heartbeat"></i> 电子层:
                <div class="health-bar">
                    <div class="health-fill" id="health-fill" style="width: 100%"></div>
                </div>
                <span id="health-value">8/8</span>
            </div>
        </div>

        <!-- 玩家列表 -->
        <div class="player-list">
            <div class="section-title">
                <span><i class="fas fa-users"></i> 玩家列表</span>
                <span id="player-count">0</span>
            </div>
            <div id="players-container">
                <!-- 玩家卡片将动态生成 -->
            </div>
        </div>

        <!-- 游戏区域 -->
        <div class="game-area">
            <!-- 手牌区域 -->
            <div class="card-section">
                <div class="section-title">
                    <span><i class="fas fa-hand-holding"></i> 我的手牌</span>
                    <span id="hand-count">0</span>
                </div>
                <div class="cards-container" id="hand-cards">
                    <!-- 手牌将动态生成 -->
                </div>
            </div>

            <!-- 反应区域 -->
            <div class="card-section">
                <div class="section-title">
                    <span><i class="fas fa-flask"></i> 反应区 (私有)</span>
                    <span id="reaction-count">0</span>
                </div>
                <div class="cards-container" id="reaction-area">
                    <!-- 反应区化合物将动态生成 -->
                </div>
            </div>

            <!-- 地板区域 -->
            <div class="card-section">
                <div class="section-title">
                    <span><i class="fas fa-th-large"></i> 实验室地板 (公开)</span>
                    <span id="floor-count">0</span>
                </div>
                <div class="cards-container" id="floor-area">
                    <!-- 地板区化合物将动态生成 -->
                </div>
            </div>
        </div>

        <!-- 操作面板 -->
        <div class="action-panel">
            <div class="action-title">
                <i class="fas fa-cogs"></i> 操作面板
            </div>

            <div class="action-buttons" id="main-buttons">
                <button class="btn btn-primary" id="btn-prepare-compound">
                    <i class="fas fa-atom"></i> 制备化合物
                </button>
                <button class="btn btn-primary" id="btn-prepare-reaction">
                    <i class="fas fa-vial"></i> 化学反应
                </button>
                <button class="btn btn-secondary" id="btn-self-rescue">
                    <i class="fas fa-first-aid"></i> 自救
                </button>
                <button class="btn btn-warning" id="btn-end-prep">
                    <i class="fas fa-flag-checkered"></i> 准备完毕
                </button>
            </div>

            <!-- 攻击操作面板 -->
            <div class="action-section" id="attack-section">
                <div class="action-section-title">
                    <i class="fas fa-fist-raised"></i> 攻击操作
                </div>
                <div class="form-group">
                    <label class="form-label">选择攻击物质:</label>
                    <div id="attack-compounds">
                        <!-- 攻击物质选项将动态生成 -->
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">选择攻击目标:</label>
                    <div class="target-list" id="attack-targets">
                        <!-- 攻击目标选项将动态生成 -->
                    </div>
                </div>
                <button class="btn btn-danger" id="btn-attack">发动攻击</button>
                <button class="btn btn-secondary" id="btn-skip-attack">跳过攻击</button>
            </div>

            <!-- 防御操作面板 -->
            <div class="action-section" id="defense-section">
                <div class="action-section-title">
                    <i class="fas fa-shield-alt"></i> 防御操作
                </div>
                <p id="attack-info">你正受到攻击！</p>
                <div class="form-group">
                    <label class="form-label">选择防御方式:</label>
                    <div class="defense-options">
                        <div>
                            <input type="radio" id="defense-existing" name="defense" value="existing">
                            <label for="defense-existing">使用现有物质防御</label>
                        </div>
                        <div>
                            <input type="radio" id="defense-gas" name="defense" value="gas">
                            <label for="defense-gas">使用稀有气体防御</label>
                        </div>
                        <div>
                            <input type="radio" id="defense-dilute" name="defense" value="dilute">
                            <label for="defense-dilute">稀释腐蚀性物质</label>
                        </div>
                        <div>
                            <input type="radio" id="defense-new" name="defense" value="new">
                            <label for="defense-new">使用新化合物防御</label>
                        </div>
                    </div>
                </div>
                <div class="defense-content" id="defense-existing-section" style="display:none;">
                    <label class="form-label">选择防御物质:</label>
                    <div id="defense-compounds">
                        <!-- 防御物质选项将动态生成 -->
                    </div>
                </div>
                <div class="defense-content" id="defense-gas-section" style="display:none;">
                    <label class="form-label">选择稀有气体:</label>
                    <div id="rare-gases">
                        <!-- 稀有气体选项将动态生成 -->
                    </div>
                </div>
                <div class="defense-content" id="defense-dilute-section" style="display:none;">
                    <label class="form-label">选择水:</label>
                    <div id="water-compounds">
                        <!-- 水化合物选项将动态生成 -->
                    </div>
                </div>
                <div class="defense-content" id="defense-new-section" style="display:none;">
                    <button class="btn btn-primary" id="btn-prepare-defense">制备防御化合物</button>
                </div>
                <button class="btn btn-primary" id="btn-defend">执行防御</button>
                <button class="btn btn-secondary" id="btn-skip-defense">跳过防御</button>
            </div>
        </div>

        <!-- 日志区域 -->
        <div class="log-area">
            <div class="log-title">
                <i class="fas fa-scroll"></i> 游戏日志
            </div>
            <div class="log-messages" id="game-log">
                <!-- 日志消息将动态添加 -->
            </div>
        </div>
    </div>

    <!-- 制备化合物模态框 -->
    <div class="modal" id="compound-modal">
        <div class="modal-content">
            <h2 class="modal-title"><i class="fas fa-atom"></i> 制备化合物</h2>
            <div class="modal-form">
                <div class="form-group">
                    <label class="form-label">选择原子/酸根:</label>
                    <div class="cards-container" id="compound-cards">
                        <!-- 化合物卡牌选项将动态生成 -->
                    </div>
                </div>

                <div class="formula-preview" id="formula-preview">H₂O</div>

                <div class="form-group">
                    <label class="form-label">化合物分子式:</label>
                    <input type="text" class="form-input" id="compound-formula" placeholder="例如: H2O">
                </div>

                <div class="form-group">
                    <label class="form-label">选择使用的卡牌:</label>
                    <div class="cards-container" id="used-cards">
                        <!-- 使用的卡牌将动态显示 -->
                    </div>
                </div>

                <div class="modal-buttons">
                    <button class="btn btn-secondary" id="btn-cancel-compound">取消</button>
                    <button class="btn btn-primary" id="btn-submit-compound">提交审核</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 反应模态框 -->
    <div class="modal" id="reaction-modal">
        <div class="modal-content">
            <h2 class="modal-title"><i class="fas fa-vial"></i> 化学反应</h2>
            <div class="modal-form">
                <div class="form-group">
                    <label class="form-label">选择反应物:</label>
                    <div class="cards-container" id="reactant-cards">
                        <!-- 反应物选项将动态生成 -->
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">选择操作卡:</label>
                    <div class="cards-container" id="action-cards">
                        <!-- 操作卡选项将动态生成 -->
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">反应方程式:</label>
                    <input type="text" class="form-input" id="reaction-equation" placeholder="例如: 2H2 + O2 → 2H2O">
                </div>

                <div class="form-group">
                    <label class="form-label">生成物:</label>
                    <input type="text" class="form-input" id="reaction-products" placeholder="例如: H2O">
                </div>

                <div class="modal-buttons">
                    <button class="btn btn-secondary" id="btn-cancel-reaction">取消</button>
                    <button class="btn btn-primary" id="btn-submit-reaction">提交审核</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 自救模态框 -->
    <div class="modal" id="rescue-modal">
        <div class="modal-content">
            <h2 class="modal-title"><i class="fas fa-first-aid"></i> 自救</h2>
            <div class="modal-form">
                <p>你处于病危状态！请选择自救资源:</p>

                <div class="target-list">
                    <div class="target-item" data-resource="oxygen">
                        <i class="fas fa-wind"></i> 使用氧气 (O₂) - 回复3点电子层
                    </div>
                    <div class="target-item" data-resource="water">
                        <i class="fas fa-tint"></i> 使用水 (H₂O) - 回复3点电子层
                    </div>
                </div>

                <div class="modal-buttons">
                    <button class="btn btn-secondary" id="btn-cancel-rescue">取消</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let socket;
        let currentPlayerSid = '';
        let currentRoomId = '';
        let gameState = {};
        let selectedCards = [];
        let selectedCompounds = [];
        let currentPlayerData = {};

        // 初始化SocketIO连接
        $(document).ready(function() {
            // 从URL获取房间ID
            const pathArray = window.location.pathname.split('/');
            currentRoomId = pathArray[pathArray.length - 1];

            // 显示房间ID
            $('#room-id').text(currentRoomId);

            // 建立SocketIO连接
            socket = io();

            // 发送连接房间请求
            socket.emit('connect_to_room', {
                room_id: currentRoomId,
                is_teacher: false
            });

            // 监听游戏状态更新
            socket.on('game_state', function(state) {
                updateGameState(state);
            });

            // 监听自己的SID
            socket.on('my_sid', function(sid) {
                currentPlayerSid = sid;
                console.log('My SID:', sid);
            });

            // 监听审核结果
            socket.on('approval_result', function(result) {
                if (result.approved) {
                    addLogMessage(`你的${result.type === 'compound' ? '化合物' : '反应'}已通过审核`, 'chemistry');
                } else {
                    addLogMessage(`你的${result.type === 'compound' ? '化合物' : '反应'}被驳回`, 'chemistry');
                }
            });

            // 监听攻击事件
            socket.on('attack_made', function(data) {
                addLogMessage(`${data.attacker} 对 ${data.target} 发动攻击，使用物质: ${data.compound.formula}`, 'attack');
            });

            // 监听游戏结束事件
            socket.on('game_over', function(data) {
                addLogMessage(`游戏结束！胜利者: ${data.winner}`, 'system');
                alert(`游戏结束！胜利者: ${data.winner}`);
            });

            socket.on('game_draw', function() {
                addLogMessage('游戏结束！平局', 'system');
                alert('游戏结束！平局');
            });

            // 监听错误
            socket.on('error', function(data) {
                alert(`错误: ${data.message}`);
            });

            // 初始化UI事件
            initUIEvents();
        });

        // 更新游戏状态
        function updateGameState(state) {
            gameState = state;

            // 更新阶段指示器
            updatePhaseIndicator(state.game_state);

            // 更新当前回合信息
            $('#current-player').text(getPlayerName(state.current_turn));

            // 更新玩家列表
            updatePlayerList(state.players);

            // 更新当前玩家数据
            if (state.players[currentPlayerSid]) {
                currentPlayerData = state.players[currentPlayerSid];

                // 更新玩家手牌
                updateHandCards();

                // 更新反应区
                updateReactionArea();

                // 更新地板区
                updateFloorArea();

                // 更新健康状态
                updateHealth();

                // 更新操作面板状态
                updateActionPanel();
            }

            // 更新攻击目标列表
            updateAttackTargets();

            // 更新防御面板
            updateDefensePanel();
        }

        // 更新阶段指示器
        function updatePhaseIndicator(phase) {
            const phaseNames = {
                'waiting': '等待中',
                'distributing': '分配阶段',
                'preparation': '准备阶段',
                'action': '行动阶段',
                'defense': '防御阶段',
                'settlement': '结算阶段'
            };

            const phaseClasses = {
                'waiting': 'gray',
                'distributing': 'phase-distributing',
                'preparation': 'phase-preparation',
                'action': 'phase-action',
                'defense': 'phase-defense',
                'settlement': 'phase-settlement'
            };

            const indicator = $('#phase-indicator');
            indicator.text(phaseNames[phase] || phase);
            indicator.removeClass().addClass('phase-indicator').addClass(phaseClasses[phase] || '');
        }

        // 更新玩家列表
        function updatePlayerList(players) {
            const container = $('#players-container');
            container.empty();
            let playerCount = 0;

            for (const sid in players) {
                const player = players[sid];
                playerCount++;

                // 跳过化学老师
                if (player.is_teacher) continue;

                const playerCard = $(`
                    <div class="player-card" data-sid="${sid}">
                        <div class="player-name">
                            <span>${player.name}</span>
                            <span class="player-role">${player.role}</span>
                        </div>
                        <div class="player-status">
                            <span>电子层: ${player.health}/8</span>
                            <span>${player.eliminated ? '已淘汰' : ''}</span>
                        </div>
                    </div>
                `);

                // 高亮当前回合玩家
                if (sid === gameState.current_turn) {
                    playerCard.addClass('current-turn');
                }

                // 高亮被攻击玩家
                if (player.is_under_attack) {
                    playerCard.addClass('under-attack');
                }

                // 标记淘汰玩家
                if (player.eliminated) {
                    playerCard.addClass('eliminated');
                }

                container.append(playerCard);
            }

            $('#player-count').text(`${playerCount} 名玩家`);
        }

        // 更新手牌显示
        function updateHandCards() {
            const container = $('#hand-cards');
            container.empty();

            if (!currentPlayerData.hand_cards) return;

            $('#hand-count').text(`${currentPlayerData.hand_cards.length} 张牌`);

            currentPlayerData.hand_cards.forEach(card => {
                let cardType = 'atom';
                if (ACID_RADICALS.includes(card)) cardType = 'acid';
                if (ACTION_CARDS.includes(card)) cardType = 'action';

                const cardElement = $(`
                    <div class="card ${cardType}" data-card="${card}">
                        <div>${formatCardLabel(card)}</div>
                        <div class="card-label">${getCardTypeLabel(card)}</div>
                    </div>
                `);

                container.append(cardElement);
            });
        }

        // 更新反应区
        function updateReactionArea() {
            const container = $('#reaction-area');
            container.empty();

            if (!currentPlayerData.reaction_area) return;

            $('#reaction-count').text(`${currentPlayerData.reaction_area.length} 种物质`);

            currentPlayerData.reaction_area.forEach(compound => {
                const compoundElement = $(`
                    <div class="card compound" data-id="${compound.id}">
                        <div>${compound.formula}</div>
                        <div class="compound-properties">
                            ${renderProperties(compound.properties)}
                        </div>
                    </div>
                `);

                container.append(compoundElement);
            });
        }

        // 渲染物质属性标签
        function renderProperties(properties) {
            if (!properties) return '';

            let html = '';
            if (properties.corrosive_concentrated) {
                html += '<span class="property-tag property-corrosive">浓腐蚀</span>';
            }
            if (properties.corrosive_diluted) {
                html += '<span class="property-tag property-corrosive">稀腐蚀</span>';
            }
            if (properties.poison) {
                html += '<span class="property-tag property-poison">有毒</span>';
            }
            if (properties.gas) {
                html += '<span class="property-tag property-gas">气体</span>';
            }

            return html;
        }

        // 更新地板区
        function updateFloorArea() {
            const container = $('#floor-area');
            container.empty();

            if (!currentPlayerData.floor_area) return;

            $('#floor-count').text(`${currentPlayerData.floor_area.length} 种物质`);

            currentPlayerData.floor_area.forEach(compound => {
                const compoundElement = $(`
                    <div class="card compound" data-id="${compound.id}">
                        <div>${compound.formula}</div>
                        <div class="compound-properties">
                            ${renderProperties(compound.properties)}
                        </div>
                    </div>
                `);

                container.append(compoundElement);
            });
        }

        // 更新健康状态
        function updateHealth() {
            const health = currentPlayerData.health || 8;
            const maxHealth = 8;
            const percent = (health / maxHealth) * 100;

            $('#health-fill').css('width', `${percent}%`);
            $('#health-value').text(`${health}/${maxHealth}`);
        }

        // 更新操作面板
        function updateActionPanel() {
            const phase = gameState.game_state;

            // 显示/隐藏主要操作按钮
            if (phase === 'preparation') {
                $('#main-buttons').show();
                $('#attack-section').hide();
                $('#defense-section').hide();
            } else if (phase === 'action') {
                $('#main-buttons').hide();
                $('#attack-section').show();
                $('#defense-section').hide();
            } else if (phase === 'defense' && currentPlayerData.is_under_attack) {
                $('#main-buttons').hide();
                $('#attack-section').hide();
                $('#defense-section').show();
            } else {
                $('#main-buttons').hide();
                $('#attack-section').hide();
                $('#defense-section').hide();
            }

            // 更新攻击物质列表
            updateAttackCompounds();
        }

        // 更新攻击物质列表
        function updateAttackCompounds() {
            const container = $('#attack-compounds');
            container.empty();

            if (!currentPlayerData.reaction_area) return;

            currentPlayerData.reaction_area.forEach(compound => {
                const compoundElement = $(`
                    <div class="target-item" data-id="${compound.id}">
                        ${compound.formula} ${renderProperties(compound.properties)}
                    </div>
                `);

                container.append(compoundElement);
            });
        }

        // 更新攻击目标列表
        function updateAttackTargets() {
            const container = $('#attack-targets');
            container.empty();

            for (const sid in gameState.players) {
                const player = gameState.players[sid];

                // 跳过自己、化学老师和淘汰玩家
                if (sid === currentPlayerSid || player.is_teacher || player.eliminated) continue;

                const targetElement = $(`
                    <div class="target-item" data-sid="${sid}">
                        ${player.name} (电子层: ${player.health}/8)
                    </div>
                `);

                container.append(targetElement);
            }
        }

        // 更新防御面板
        function updateDefensePanel() {
            if (!currentPlayerData.is_under_attack) return;

            // 更新防御物质列表
            const defenseContainer = $('#defense-compounds');
            defenseContainer.empty();

            if (currentPlayerData.reaction_area) {
                currentPlayerData.reaction_area.forEach(compound => {
                    const compoundElement = $(`
                        <div class="target-item" data-id="${compound.id}">
                            ${compound.formula} ${renderProperties(compound.properties)}
                        </div>
                    `);

                    defenseContainer.append(compoundElement);
                });
            }

            // 更新稀有气体列表
            const gasContainer = $('#rare-gases');
            gasContainer.empty();

            if (currentPlayerData.hand_cards) {
                const rareGases = currentPlayerData.hand_cards.filter(card =>
                    ['Ar', 'He', 'Ne'].includes(card)
                );

                rareGases.forEach(gas => {
                    const gasElement = $(`
                        <div class="target-item" data-gas="${gas}">
                            ${gas}
                        </div>
                    `);

                    gasContainer.append(gasElement);
                });
            }

            // 更新水物质列表
            const waterContainer = $('#water-compounds');
            waterContainer.empty();

            if (currentPlayerData.reaction_area) {
                const waterCompounds = currentPlayerData.reaction_area.filter(
                    compound => compound.formula === 'H2O'
                );

                waterCompounds.forEach(water => {
                    const waterElement = $(`
                        <div class="target-item" data-id="${water.id}">
                            ${water.formula}
                        </div>
                    `);

                    waterContainer.append(waterElement);
                });
            }
        }

        // 初始化UI事件
        function initUIEvents() {
            // 制备化合物按钮
            $('#btn-prepare-compound').click(openCompoundModal);

            // 准备反应按钮
            $('#btn-prepare-reaction').click(openReactionModal);

            // 自救按钮
            $('#btn-self-rescue').click(openRescueModal);

            // 准备完毕按钮
            $('#btn-end-prep').click(function() {
                socket.emit('end_preparation');
            });

            // 攻击按钮
            $('#btn-attack').click(function() {
                const selectedCompound = $('.target-item.selected', '#attack-compounds').data('id');
                const targetPlayer = $('.target-item.selected', '#attack-targets').data('sid');

                if (!selectedCompound || !targetPlayer) {
                    alert('请选择攻击物质和目标');
                    return;
                }

                socket.emit('attack', {
                    target_sid: targetPlayer,
                    compound_id: selectedCompound
                });
            });

            // 跳过攻击按钮
            $('#btn-skip-attack').click(function() {
                socket.emit('skip');
            });

            // 防御方式选择
            $('input[name="defense"]').change(function() {
                $('.defense-content').hide();
                $(`#defense-${this.value}-section`).show();
            });

            // 执行防御按钮
            $('#btn-defend').click(function() {
                const defenseType = $('input[name="defense"]:checked').val();
                let defenseData = { action: defenseType };

                switch (defenseType) {
                    case 'existing':
                        const compoundId = $('.target-item.selected', '#defense-compounds').data('id');
                        if (!compoundId) {
                            alert('请选择防御物质');
                            return;
                        }
                        defenseData.compound_id = compoundId;
                        break;

                    case 'gas':
                        const gas = $('.target-item.selected', '#rare-gases').data('gas');
                        if (!gas) {
                            alert('请选择稀有气体');
                            return;
                        }
                        defenseData.gas = gas;
                        break;

                    case 'dilute':
                        const waterId = $('.target-item.selected', '#water-compounds').data('id');
                        if (!waterId) {
                            alert('请选择水');
                            return;
                        }
                        defenseData.water_id = waterId;
                        break;

                    case 'new':
                        addLogMessage('请先制备防御化合物', 'system');
                        return;
                }

                socket.emit('defend', defenseData);
            });

            // 跳过防御按钮
            $('#btn-skip-defense').click(function() {
                socket.emit('skip');
            });

            // 目标选择
            $(document).on('click', '.target-item', function() {
                $(this).siblings().removeClass('selected');
                $(this).addClass('selected');
            });

            // 提交化合物审核
            $('#btn-submit-compound').click(function() {
                const formula = $('#compound-formula').val().trim();
                if (!formula) {
                    alert('请输入化合物分子式');
                    return;
                }

                if (selectedCards.length === 0) {
                    alert('请选择至少一张卡牌');
                    return;
                }

                socket.emit('prepare_compound', {
                    compound: formula,
                    cards_used: selectedCards,
                    is_for_defense: false
                });

                $('#compound-modal').hide();
            });

            // 提交反应审核
            $('#btn-submit-reaction').click(function() {
                const equation = $('#reaction-equation').val().trim();
                const products = $('#reaction-products').val().trim();

                if (!equation || !products) {
                    alert('请填写反应方程式和生成物');
                    return;
                }

                socket.emit('prepare_reaction', {
                    equation: equation,
                    products: products.split(',').map(p => p.trim()),
                    reactants: selectedCompounds,
                    action_cards: selectedCards
                });

                $('#reaction-modal').hide();
            });
        }

        // 打开制备化合物模态框
        function openCompoundModal() {
            const modal = $('#compound-modal');
            const cardsContainer = $('#compound-cards');
            cardsContainer.empty();

            // 添加可用的卡牌
            currentPlayerData.hand_cards.forEach(card => {
                let cardType = 'atom';
                if (ACID_RADICALS.includes(card)) cardType = 'acid';
                if (ACTION_CARDS.includes(card)) cardType = 'action';

                const cardElement = $(`
                    <div class="card ${cardType}" data-card="${card}">
                        <div>${formatCardLabel(card)}</div>
                        <div class="card-label">${getCardTypeLabel(card)}</div>
                    </div>
                `);

                cardsContainer.append(cardElement);
            });

            // 卡牌选择事件
            $('.card', cardsContainer).click(function() {
                const card = $(this).data('card');

                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    selectedCards = selectedCards.filter(c => c !== card);
                } else {
                    $(this).addClass('selected');
                    selectedCards.push(card);
                }

                // 更新已选卡牌显示
                updateUsedCards();
            });

            modal.show();
        }

        // 更新已选卡牌显示
        function updateUsedCards() {
            const container = $('#used-cards');
            container.empty();

            selectedCards.forEach(card => {
                let cardType = 'atom';
                if (ACID_RADICALS.includes(card)) cardType = 'acid';
                if (ACTION_CARDS.includes(card)) cardType = 'action';

                const cardElement = $(`
                    <div class="card ${cardType}">
                        <div>${formatCardLabel(card)}</div>
                        <div class="card-label">${getCardTypeLabel(card)}</div>
                    </div>
                `);

                container.append(cardElement);
            });
        }

        // 打开反应模态框
        function openReactionModal() {
            const modal = $('#reaction-modal');
            const reactantsContainer = $('#reactant-cards');
            const actionsContainer = $('#action-cards');

            reactantsContainer.empty();
            actionsContainer.empty();
            selectedCompounds = [];
            selectedCards = [];

            // 添加反应物
            currentPlayerData.reaction_area.forEach(compound => {
                const compoundElement = $(`
                    <div class="card compound" data-id="${compound.id}">
                        <div>${compound.formula}</div>
                        <div class="compound-properties">
                            ${renderProperties(compound.properties)}
                        </div>
                    </div>
                `);

                reactantsContainer.append(compoundElement);
            });

            // 添加操作卡
            currentPlayerData.hand_cards.forEach(card => {
                if (ACTION_CARDS.includes(card)) {
                    const cardElement = $(`
                        <div class="card action" data-card="${card}">
                            <div>${card}</div>
                            <div class="card-label">操作牌</div>
                        </div>
                    `);

                    actionsContainer.append(cardElement);
                }
            });

            // 反应物选择事件
            $('.card', reactantsContainer).click(function() {
                const id = $(this).data('id');

                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    selectedCompounds = selectedCompounds.filter(c => c !== id);
                } else {
                    $(this).addClass('selected');
                    selectedCompounds.push(id);
                }
            });

            // 操作卡选择事件
            $('.card', actionsContainer).click(function() {
                const card = $(this).data('card');

                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    selectedCards = selectedCards.filter(c => c !== card);
                } else {
                    $(this).addClass('selected');
                    selectedCards.push(card);
                }
            });

            modal.show();
        }

        // 打开自救模态框
        function openRescueModal() {
            // 只有健康值小于8时才能自救
            if (currentPlayerData.health >= 8) {
                alert('你的电子层已满，无需自救');
                return;
            }

            $('#rescue-modal').show();

            // 自救资源选择
            $('.target-item', '#rescue-modal').click(function() {
                const resource = $(this).data('resource');
                socket.emit('self_rescue', { resource: resource });
                $('#rescue-modal').hide();
            });
        }

        // 添加日志消息
        function addLogMessage(message, type = 'system') {
            const logContainer = $('#game-log');
            const logMessage = $(`
                <div class="log-message ${type}">
                    <i class="fas fa-info-circle"></i> ${new Date().toLocaleTimeString()}: ${message}
                </div>
            `);

            logContainer.append(logMessage);
            logContainer.scrollTop(logContainer[0].scrollHeight);
        }

        // 辅助函数：获取玩家名称
        function getPlayerName(sid) {
            return gameState.players[sid]?.name || sid;
        }

        // 辅助函数：格式化卡牌标签
        function formatCardLabel(card) {
            // 简单的格式化，比如H2O应该显示为H₂O
            return card.replace(/2/g, '₂').replace(/3/g, '₃');
        }

        // 辅助函数：获取卡牌类型标签
        function getCardTypeLabel(card) {
            if (ATOMS.includes(card)) return '原子';
            if (ACID_RADICALS.includes(card)) return '酸根';
            if (ACTION_CARDS.includes(card)) return '操作';
            return '未知';
        }

        // 卡牌配置常量
        const ATOMS = ['H', 'C', 'O', 'N', 'F', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'K', 'Ca',
             'Mn', 'Fe', 'Cu', 'Zn', 'Li', 'Ag', 'I', 'Ba', 'Ar', 'He', 'Ne'];
        const ACID_RADICALS = ['OH', 'SO4', 'HSO4', 'NO3', 'CO3', 'HCO3', 'NH4', 'PO4'];
        const ACTION_CARDS = ['点燃', '加热', '催化剂', '通电'];
    </script>
</body>
</html>